package sk.tramtatiri;

import java.util.List;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

import sk.tramtatiri.data.dao.interfaces.UserDao;
import sk.tramtatiri.data.dataobjects.User;

public class EmailAddrExistValidator implements IValidator<String> {

	private static final long serialVersionUID = 3287726083251083402L;
	
	private UserDao userDao;
	
	public EmailAddrExistValidator(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public void validate(IValidatable<String> validatable) {
		List<User> users = userDao.findAll();
		final String value = validatable.getValue();
		if (userDao.countAll()>0) {
			for (User u:users) {
				if (u.getEmail().equalsIgnoreCase(value)) {
					ValidationError error = new ValidationError();
					error.setMessage("Email \"" + value + "\" already exists.");
					validatable.error(error);
				}
			}
		}
	}

}
